import {
	IContext,
	IParam,
	computedNavData,
	deepCopy,
	getSessionStorage,
} from '@/core';
import { getCookie } from 'qx-util';
import { Ref } from 'vue';

/**
 * 处理编辑器导航参数
 *
 * @export
 * @param {Record<string, any>} props
 * @return {*}
 */
export function handleEditorNavParams(props: Record<string, any>) {
	const { localContext, localParam, data } = props;
	const { context, viewParams } = useContextParams(props);
	const navParams = {
		navContext: context.value,
		navViewParam: viewParams.value,
	};
	if (localContext && Object.keys(localContext).length > 0) {
		const _context = computedNavData(
			data,
			navParams.navContext,
			navParams.navViewParam,
			localContext
		);
		Object.assign(navParams.navContext, _context);
	}
	if (localParam && Object.keys(localParam).length > 0) {
		const _param = computedNavData(
			data,
			navParams.navContext,
			navParams.navViewParam,
			localParam
		);
		Object.assign(navParams.navViewParam, _param);
	}
	return navParams;
}

/**
 * 处理上下文参数
 *
 * @export
 * @param {Record<any, any>} props
 * @return {*}
 */
export function useContextParams(props: Record<any, any>) {
	const { context, viewParams } = props;
	// 维护上下文并监控其变化
	const _context: Ref<IContext> = ref({});
	watch(
		() => context,
		(newVal: any, oldVal: any) => {
			_context.value = deepCopy(newVal || {});
		},
		{
			immediate: true,
			deep: true,
		}
	);
	// 维护视图参数并监控其变化
	const _viewParams: Ref<IParam> = ref({});
	watch(
		() => viewParams,
		(newVal: any, oldVal: any) => {
			_viewParams.value = deepCopy(newVal || {});
		},
		{
			immediate: true,
			deep: true,
		}
	);
	return { context: _context, viewParams: _viewParams };
}

// 获取文件上传路径
export function getUploadUrl(): string {
	return App.getProjectSetting().uploadFileUrl;
}

//获取文件下载路径
export function getDownloadUrl(): string {
	return App.getProjectSetting().exportFileUrl;
}

//获取文件请求头
export function getRequestingHeader(): IParam {
	let headers: IParam = {};
	if (App.getProjectSetting().saasMode) {
		let activeOrgData = getSessionStorage('activeOrgData');
		headers['srforgid'] = activeOrgData?.orgid;
		headers['srfsystemid'] = activeOrgData?.systemid;
	}
	if (getCookie('ibzuaa-token')) {
		headers['Authorization'] = `Bearer ${getCookie('ibzuaa-token')}`;
	} else {
		// 第三方应用打开免登
		if (sessionStorage.getItem('srftoken')) {
			const token = sessionStorage.getItem('srftoken');
			headers['Authorization'] = `Bearer ${token}`;
		}
	}
	return headers;
}
// 编辑器数据类型参数接口
interface IEditorTypeParams {
    valueType?: string;
    valueSeparator?: string;
    textSeparator?: string;
    objectIdField?: string;
    objectNameField?: string;
    objectValueField?: string;
}

// 处理编辑器数据类型相关参数（VALUETYPE/VALUESEPARATOR/TEXTSEPARATOR/OBJECTIDFIELD/OBJECTNAMEFIELD/OBJECTVALUEFIELD）
export function useEditorTypeParams(params: IParam = {}) {
    const editorTypeParams: IEditorTypeParams = {};
    const compAttrs: IParam = useAttrs();
    const editorType = compAttrs.editorType;
    const editorStyle = compAttrs.editorStyle;
    if (compAttrs.VALUETYPE) {
        editorTypeParams.valueType = compAttrs.VALUETYPE;
    }
    if (compAttrs.VALUESEPARATOR) {
        editorTypeParams.valueSeparator = compAttrs.VALUESEPARATOR;
    }
    if (compAttrs.TEXTSEPARATOR) {
        editorTypeParams.textSeparator = compAttrs.TEXTSEPARATOR;
    }
    if (compAttrs.OBJECTIDFIELD) {
        editorTypeParams.objectIdField = compAttrs.OBJECTIDFIELD;
    }
    if (compAttrs.OBJECTNAMEFIELD) {
        editorTypeParams.objectNameField = compAttrs.OBJECTNAMEFIELD;
    }
    if (compAttrs.OBJECTVALUEFIELD) {
        editorTypeParams.objectValueField = compAttrs.OBJECTVALUEFIELD;
    }
    // 校验方法
    const validateConfig = () => {
        let result: boolean = true;
        if (!editorTypeParams.valueType) {
            return result;
        }
        switch (editorType) {
			case 'MOBDATE': // 时间选择器
			case 'MOBDATE_SECOND': // 时间选择器(YYYY-MM-DD HH:mm:ss)
			case 'MOBDATE_NOTIME': // 时间选择器(YYYY-MM-DD)
			case 'MOBDATE_NODAY_NOSECOND': // 时间选择器(HH:mm)
			case 'MOBDATE_NODAY': // 时间选择器(HH:mm:ss)
			case 'MOBDATE_MINUTE': // 时间选择器（YYYY-MM-DD HH:mm）
			case 'MOBDATE_HOUR': // 时间选择器（YYYY-MM-DD HH）
			case 'MOBSTEPPER': // 步进器
			case 'MOBCOLORPICKER': // 颜色选择器
			case "MOBNUMBERRANGE": // 数值范围编辑框
			case 'MOBRATING': // 评分器
			case 'MOBDATERANGE': //时间范围选择器
			case 'MOBDATERANGE_NOTIME': //时间范围选择器(YYYY-MM-DD)
				if (editorTypeParams.valueType !== 'SIMPLE') {
                    console.error(`${editorType}类型编辑器不支持非SIMPLE数据类型`);
                    result = false;
                }
                break;
			case "MOBARRAY": //数组编辑器
                if (editorTypeParams.valueType !== 'SIMPLES') {
                    console.error(`${editorType}类型编辑器不支持非SIMPLES数据类型`);
                    result = false;
                }
                break;
			case 'MOBSLIDER': // 滑动输入条
            case 'MOBCHECKLIST': // 下拉列表多选
                if (!(editorTypeParams.valueType === 'SIMPLE' || editorTypeParams.valueType === 'SIMPLES')) {
                    console.error(`${editorType}类型编辑器不支持非SIMPLE、SIMPLES数据类型`);
                    result = false;
                }
                break;
			case "MOBPICTURE": // 图片控件（单项）
			case "MOBPICTURE_RAW": // 图片控件（单项、直接内容）
			case 'MOBSINGLEFILEUPLOAD': // 文件控件（单项）
				if (!(editorTypeParams.valueType === 'SIMPLE' || editorTypeParams.valueType === 'OBJECT')) {
					console.error(`${editorType}类型编辑器不支持非SIMPLE、OBJECT数据类型`);
					result = false;
				}
				break;
			case 'MOBMULTIFILEUPLOAD': // 文件控件(多项)
			case 'MOBPICTURELIST': // 图片控件(多项)
					if (!(editorTypeParams.valueType === 'SIMPLE' || editorTypeParams.valueType === 'OBJECT' || editorTypeParams.valueType === 'OBJECTS')) {
						console.error(`${editorType}类型编辑器不支持非SIMPLE、OBJECT、OBJECTS数据类型`);
						result = false;
					}
					break;
            case 'MOBDROPDOWNLIST': // 下拉列表单选
                // 自定义数据源下拉树
                if (editorStyle == 'TREEDROPDOWNLIST') {
                    if (!(editorTypeParams.valueType === 'SIMPLE' || editorTypeParams.valueType === 'SIMPLES' || editorTypeParams.valueType === 'OBJECT' || editorTypeParams.valueType === 'OBJECTS')) {
                        console.error(`${editorType}类型编辑器不支持非SIMPLE、SIMPLES、OBJECT、OBJECTS数据类型`);
                        result = false;
                    }
                } else if (editorTypeParams.valueType !== 'SIMPLE') {
                    console.error(`${editorType}类型编辑器不支持非SIMPLE数据类型`);
                    result = false;
                }
                break;
        }
        return result;
    }
    return {
        ...editorTypeParams,
        validateConfig,
    };
}